<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/5-2022-10-13-lidare.css">
</head>

<body>
    <select class="province">
    </select>
    <select class="city">
    </select>
    <select class="area">
    </select>
    <!-- 引入js文件，里面有一个allList，存有数据 -->
    <script src="./data/5-2022-10-13-lidare.js"></script>
    <script>
        // console.log(allList);
        var provinceNode = document.querySelector(".province");
        provinceNode.dataset.name = "";//初始化
        var cityNode = document.querySelector(".city");
        cityNode.dataset.name = "";
        var areaNode = document.querySelector(".area");
        provinceNode.innerHTML = `<option value="" disabled>选择市</option>`;
        for (var key in allList) {
            var option = document.createElement("option");
            option.value = key;
            option.textContent = allList[key].name;
            provinceNode.appendChild(option);
        }
        provinceNode.onchange = function () {
            this.dataset.name = this.value;
            cityNode.innerHTML = `<option value="" disabled>选择市</option>`;
            areaNode.innerHTML = `<option value="" disabled>选择区</option>`;
            [].forEach.call(allList[this.value].city, function (item) {
                var option = document.createElement("option");
                option.value = item.code;
                option.textContent = item.name;
                cityNode.appendChild(option);
            });
            //使用onchange遇上只有一个城市会出现问题，需要处理
            if(allList[this.value].city.length){
                cityNode.dataset.value = allList[this.value].city[0].code;
                cityNode.onchange();
            }
        }
        cityNode.onchange = function () {
            this.dataset.name = this.value;
            [].forEach.call(allList[provinceNode.dataset.name].city, function (item) {
                if(parseInt(item.code)==parseInt(cityNode.dataset.name)){
                    areaNode.innerHTML = `<option value="" disabled>选择区</option>`;
                    [].forEach.call(item.area, function(item){
                        var option = document.createElement("option");
                        option.value = item.code;
                        option.textContent = item.name;
                        areaNode.appendChild(option);
                    })
                }
            })
        }
        provinceNode.onchange();
        // cityNode.onchange();
    </script>
</body>

</html>